import { getToken, removeToken, setTimeStamp, setToken } from '@/utils/auth'
import { getUserInfo, login, getUserInfoaApi } from '@/api/user'

const state = {
  token: getToken(),
  userinfo: {}
}
const mutations = {
  handleLogin(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  setUserInfo(state, userInfor) {
    state.userinfo = userInfor
  },
  removetoken(state) {
    state.token = null
    removeToken()
  },
  removeUserinfo(state) {
    state.userinfo = {}
  }
}
const actions = {
  async loginAction(ctx, data) {
    const res = await login(data)
    ctx.commit('handleLogin', res)
    setTimeStamp()
  },
  async getUserInfo(ctx) {
    const res = await getUserInfo()
    console.log(res)
    const arr = await getUserInfoaApi(res.userId)
    console.log(arr)
    ctx.commit('setUserInfo', { ...res, ...arr })
  },
  logoutSAction(ctx) {
    ctx.commit('removetoken'),
    ctx.commit('removeUserinfo')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

